package com.woniu.mealsService.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.woniu.exception.meals.OrderException;
import com.woniu.mealsService.config.AliPayConfig;
import com.woniu.mealsService.data.OrderStatus;
import com.woniu.mealsService.service.OrderProductService;
import com.woniu.utils.EnumException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author jiang
 */
@Controller
@RequestMapping("alipay")
@Api(tags = "支付宝异步回调")
public class AlipayController {
    @Autowired
    private AliPayConfig aliPayConfig;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostMapping("/payCallback")
    @ApiOperation(value = "支付回调请求接口")
    public String payCallback(HttpServletRequest request) throws  Exception {
        System.out.println("支付回调请求接口");
        Map<String,String> map = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println(parameterMap);
        for (Iterator<String> iterator = parameterMap.keySet().iterator(); iterator.hasNext();){
            String reqName = iterator.next();
            String[] reqValues = parameterMap.get(reqName);
            String reqValueStr = StringUtil.join(reqValues, ",");
            map.put(reqName,reqValueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(map, aliPayConfig.getAlipayPublicKey(), "utf-8", "RSA2");
        if (signVerified){
            if("TRADE_SUCCESS".equals(map.get("trade_status"))){
                //支付成功，修改支付状态
                orderProductService.updateOrder(map.get("out_trade_no"), OrderStatus.ORDER_PAID);
                return "交易支付成功";
            }else{
                rabbitTemplate.convertAndSend("delay_alipay_status", map.get("out_trade_no"));
                return orderProductService.alipayQuery(map.get("out_trade_no"));
            }
        }

        throw new OrderException(EnumException.ALIPAY_ERROR_EXCEPTION);
    }
}
